from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from itsdangerous import BadData

from . import constants


def check_access_token(access_token_openid):
    """
    反序列化openid
    :param access_token_openid: openid明文
    :return: openid密文
    """
    # 创建一个序列化对象
    s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)

    # 反序列化
    try:
        data = s.loads(access_token_openid)
    except BadData:
        return None
    else:
        # 返回openid
        return data.get('openid')

def generate_access_token(openid):
    """
    序列化openid
    :param openid: 用户的openid
    :return: 序列化openid
    """
    # 创建一个序列化对象
    s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)

    # 准备待序列化的字典数据
    data = {"openid": openid}

    # 调用dumps方法进行序列化
    token = s.dumps(data)

    # 返回序列化数据
    return token.decode()
